package com.realtybaron.api;

import com.google.inject.Singleton;
import com.realtybaron.auction.AnswerInquiry;
import com.realtybaron.common.Link;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.filter.LoggingFilter;
import com.sun.jersey.core.util.MultivaluedMapImpl;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import java.io.IOException;

/**
 * User: marc Date: Feb 3, 2010 Time: 7:20:35 AM
 * <p/>
 * THIS SOFTWARE IS COPYRIGHTED.  THE SOFTWARE MAY NOT BE COPIED REPRODUCED, TRANSLATED, OR REDUCED TO ANY ELECTRONIC MEDIUM OR MACHINE READABLE FORM WITHOUT THE PRIOR WRITTEN CONSENT OF SOCO
 * TECHNOLOGIES.
 */
@Singleton
public class AnswerInquiryController extends AbstractWebController {
  /**
   * @param req web request
   * @param res web response
   * @throws javax.servlet.ServletException
   * @throws java.io.IOException
   */
  @Override
  protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    this.resolver.handle(req, res, "inquiry");
  }
  @Override
  protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    Client client = Client.create();
    client.addFilter(new LoggingFilter(System.out));
    WebResource resource = client.resource(this.apiBase + "/inquiry/answer/" + req.getParameter("id"));
    MultivaluedMap<String, String> params = new MultivaluedMapImpl();
    params.add("text", req.getParameter("text"));
    params.add("api_key", this.apiKey);
    AnswerInquiry result = resource.type(MediaType.APPLICATION_FORM_URLENCODED).accept(MediaType.APPLICATION_XML).post(AnswerInquiry.class, params);
    if (result.getStatus().getCode() == HttpServletResponse.SC_OK) {
      for (Link link : result.getLinks().getLink()) {
        if (link.getRel().equals("auction")) {
          this.resolver.handle(req, res, "redirect:" + link.getHref());
        }
      }
    } else {
      req.setAttribute("messages", result.getStatus().getMessages().getMessage());
      this.resolver.handle(req, res, "inquiry");
    }
  }
}